package com.czk.gulimall.coupon.service.impl;

import com.czk.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.czk.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;

import com.czk.gulimall.coupon.dao.SeckillSessionDao;
import com.czk.gulimall.coupon.entity.SeckillSessionEntity;
import com.czk.gulimall.coupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Autowired
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLatest3DaysSession() {
        // 计算最近三天
        LocalDate today=LocalDate.now();
        //
        LocalDate plus = today.plus(Duration.ofDays(2));

        // 2022-06-14 00:00:00
        LocalDateTime todayTime=LocalDateTime.of(today, LocalTime.MIN);
        // 2022-06-17 23:59:59
        LocalDateTime plusTime = LocalDateTime.of(plus, LocalTime.MAX);

        String start = todayTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
        String end = plusTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));

        List<SeckillSessionEntity> entityList = this.list(new QueryWrapper<SeckillSessionEntity>().between("start_time", start, end));
        if (entityList!=null&&entityList.size() > 0){
            List<SeckillSessionEntity> collect = entityList.stream().map(x -> {
                Long id = x.getId();
                // 根据活动id查询关联商品
                List<SeckillSkuRelationEntity> promotion_session_id = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", id));
                x.setRelationSkus(promotion_session_id);
                return x;
            }).collect(Collectors.toList());
            return collect;
        }
        return new ArrayList<>();
    }
}